using System.Xml;
using System.Xml.Serialization;
using WroxGallery.Models.Interfaces;

namespace WroxGallery.Models.Implementations
{
    public class XmlConfigurationRepository: IConfigurationRepository
    {
        private GalleryConfiguration configuration;
        private string _configfileName;

        public XmlConfigurationRepository(string configfileName)
        {
            _configfileName = configfileName;
            LoadConfig();
        }

        private void LoadConfig()
        {
            XmlSerializer serializer = new XmlSerializer(typeof(GalleryConfiguration));
            using (XmlReader reader = XmlReader.Create(_configfileName))
            {
                object deserialized = serializer.Deserialize(reader);
                if (deserialized != null)
                    configuration = deserialized as GalleryConfiguration;
                else
                {
                    configuration = new GalleryConfiguration();
                }
            }
        }

        public void Store()
        {
            XmlSerializer serializer = new XmlSerializer(typeof(GalleryConfiguration));
            using (XmlWriter writer = XmlWriter.Create(_configfileName))
            {
                serializer.Serialize(writer, configuration);
            }
            LoadConfig();
        }

        public string GalleryName
        {
            get { return configuration.GalleryName; }
        }

        public string FickerUserName
        {
            get { return configuration.FlickrUserName; }
        }

        public string About
        {
            get { return configuration.About; }
        }

        public bool ValidateUser(string username, string password)
        {
            if(username.Equals(configuration.Username)
                && password.Equals(configuration.Password))
                return true;
            return false;
        }

        public GalleryConfiguration Config
        {
            get { return configuration; }
            set { configuration = value; }
        }
    }
}